﻿from random import *
from turtle import *
import time
from queue import Queue
import _thread
from os import *
# 常量定义
N=100 #最多操作数
M=2 #大本营间最近曼哈顿距离
n=int(input())
m=int(input())
color=['grey','red','blue']
screensize(canvwidth=2000, canvheight=2000, bg='black')
#变量定义&初始化
turn=0
numofmount=n*m #山与塔的数量和
numofcastle=0
numofswamp=0
numofland=n*m-numofmount-numofswamp #空地的数量
numofplayers=2
numofdieplayer=0 #死亡玩家数
delay(0)

register_shape('pictures\\block_red.gif')
register_shape('pictures\\block_blue.gif')
register_shape('pictures\\block_grey.gif')
register_shape('pictures\\mount.gif')
register_shape('pictures\\castle.gif')
register_shape('pictures\\home.gif')
register_shape('pictures\\swamp.gif')
register_shape('pictures\\highlight.gif')

#

class Block:
    def __init__(self,ty):
        self.type=int(ty) #0地 1山 2塔 3大本营 4沼泽
        self.army=0
        self.color=0
        if self.type==2:
            self.army=choice(range(40,50))
        self.lazytag=True
map=[0]
for i in range(1,n+1):
    map.append([0])
    inp=input().split()
    print(inp)
    for j in range(1,m+1):
        map[i].append(Block(inp[j-1]))

player=[0]
class Players:
    def __init__(self,nn):
        self.die=False
        self.color=nn
        self.army=0
        self.land=1
        self.castle=1
        self.operate=Queue(maxsize=N)
        con=1
        while con:
            x = choice(range(1,n+1))
            y = choice(range(1,m+1))
            if(map[x][y].type!=0):continue
            for i in range(1, nn - 1 + 1):
                xa=player[i].home[0]
                ya=player[i].home[1]
                if (abs(xa - x) + abs(ya - y) <= M):
                    break
            else:
                con=0
                self.home=(x,y)
                self.highlight = [x,y]
                map[x][y].type=3
                map[x][y].color=nn
                map[x][y].army=1
        self.p=Pen()
        self.p.up()
        self.p.shape('pictures\\highlight.gif')
        self.p.pensize(800/min(m,n))
        self.p.goto(800/min(m,n)*self.highlight[1]-400-400/min(m,n),-800/min(m,n)*self.highlight[0]+400+400/min(m,n))
    def kill(self,p):# 俘获玩家p (函数名改成capture?)
        # 修改player.army,land!!
        global numofdieplayer
        map[player[p].home[0]][player[p].home[1]].type=2
        for i in range(1,n+1):
            for j in range(1,m+1):
                if(map[i][j].color==p):
                    map[i][j].color=self.color
                    map[i][j].army=(map[i][j].army+1)//2
                    map[i][j].lazytag=True
        player[p].die=True
        numofdieplayer+=1
for i in range(1,numofplayers+1):
    player.append(Players(i))
#显示
def printmap():
    p=Pen()
    p.up()
    p.ht()
    p.color('white')
    p.speed(0)
    tracer(False)
    p.pensize(800/min(m,n)-2)
    for i in range(1,n+1):
        for j in range(1,m+1):
            if not map[i][j].lazytag: continue
            map[i][j].lazytag=False
            p.goto(800/min(m,n)*j-400-400/min(m,n),-800/min(m,n)*i+400+400/min(m,n))
            p.shape('pictures\\block_'+color[map[i][j].color]+'.gif')
            p.stamp()
            p.goto(800/min(m,n)*j-400-400/min(m,n),-800/min(m,n)*i+400+400/min(m,n))
            if map[i][j].type==1:
                p.shape('pictures\\mount.gif')
            elif map[i][j].type==2:
                p.shape('pictures\\castle.gif')
            elif map[i][j].type==3:
                p.shape('pictures\\home.gif')
            elif map[i][j].type==4:
                p.shape('pictures\\swamp.gif')
            if map[i][j].type!=0:
                p.stamp()
            p.goto(800/min(m,n)*j-400-400/min(m,n),-800/min(m,n)*i+400+200/min(m,n))
            if map[i][j].army!=0:
                p.write(map[i][j].army,font=('Arial',30,'normal'),align='center')
    update()
    system('cls')
    for j in range(m+2):
        print("___",end="")
    print("")
    for i in range(1,n+1):
        print("|",end="")
        for j in range(1,m+1):
            if [i,j]==player[1].highlight:
                print("(%3d)"%(map[i][j].army),end="")
            elif [i,j]==player[2].highlight:
                print("[%3d]"%(map[i][j].army),end="")
            else:
                print("%5d"%(map[i][j].army),end="")
            if map[i][j].type==1:
                print("M",end="")
            elif map[i][j].type==2:
                print("C",end="")
            elif map[i][j].type==3:
                print("H",end="")
            elif map[i][j].type==4:
                print("S",end="")
            else: print(" ",end="")
        print("|")
    for j in range(m+2):
        print("___",end="")
    print("")
    print(r1,r2,player[1].highlight,player[2].highlight)
#游戏进程
def mymain():
    global turn
    p=Pen()
    p.up()
    p.ht()
    p.color('white')
    p.speed(0)
    tracer(False)
    while numofdieplayer<numofplayers-1:
        turn+=1
        for rsx in range(2):
            printmap()
            time.sleep(0.5)
            for mover in range(1,numofplayers+1):
                if player[mover].die: continue
                if player[mover].operate.empty(): continue
                move=player[mover].operate.get(False)
                if map[move.tx][move.ty].type==1: continue#
                if map[move.fx][move.fy].color!=mover: continue#
                movenum=int(move.num*map[move.fx][move.fy].army)
                if movenum==map[move.fx][move.fy].army: movenum-=1
                if movenum==0: continue#
                map[move.fx][move.fy].lazytag=True
                map[move.tx][move.ty].lazytag=True
                map[move.fx][move.fy].army-=movenum
                if (map[move.tx][move.ty].type==0 or map[move.tx][move.ty].type==4):        # 平地or沼泽
                    if map[move.tx][move.ty].color==0:                                          #无归属
                        map[move.tx][move.ty].army+=movenum
                        map[move.tx][move.ty].color=player[mover].color
                        player[mover].land+=1
                    elif map[move.tx][move.ty].color==player[mover].color:                      #己方
                        map[move.tx][move.ty].army+=movenum
                    else:                                                                       #敌方
                        if movenum>map[move.tx][move.ty].army:                                      #占领
                            map[move.tx][move.ty].army=movenum-map[move.tx][move.ty].army
                            player[mover].army-=movenum-map[move.tx][move.ty].army
                            player[mover].land+=1
                            player[map[move.tx][move.ty].color].army-=movenum-map[move.tx][move.ty].army
                            player[map[move.tx][move.ty].color].land-=1
                            map[move.tx][move.ty].color=player[mover].color
                        else:                                                                       #未占领
                            map[move.tx][move.ty].army-=movenum
                            player[mover].army-=movenum
                            player[map[move.tx][move.ty].color].army-=movenum
                            
                else:                                                                       # 塔or大本营
                    if map[move.tx][move.ty].color==0:                                          #无归属
                        if movenum>map[move.tx][move.ty].army:                                      #占领
                            map[move.tx][move.ty].army=movenum-map[move.tx][move.ty].army
                            map[move.tx][move.ty].color=player[mover].color
                            player[mover].army-=movenum-map[move.tx][move.ty].army
                            player[mover].land+=1
                            player[mover].castle+=1
                        else:                                                                       #未占领
                            map[move.tx][move.ty].army-=movenum
                            player[mover].army-=movenum
                    elif map[move.tx][move.ty].color==player[mover].color:                      #己方
                        map[move.tx][move.ty].army+=movenum
                    else:                                                                       #敌方
                        if movenum>map[move.tx][move.ty].army:                                      #占领
                            player[mover].army-=movenum-map[move.tx][move.ty].army
                            player[mover].land+=1
                            player[mover].castle+=1
                            player[map[move.tx][move.ty].color].army-=movenum-map[move.tx][move.ty].army
                            player[map[move.tx][move.ty].color].land-=1
                            player[map[move.tx][move.ty].color].castle-=1
                            if(map[move.tx][move.ty].type==3): player[mover].kill(map[move.tx][move.ty].color) #占领大本营则消灭敌人
                            map[move.tx][move.ty].army=movenum-map[move.tx][move.ty].army
                            map[move.tx][move.ty].color=player[mover].color

                        else:                                                                       #未占领
                            map[move.tx][move.ty].army-=movenum
                            player[mover].army-=movenum
                            player[map[move.tx][move.ty].color].army-=movenum
        #更新士兵数目
        for i in range(1,n+1):
            for j in range(1,m+1):
                if (map[i][j].color!=0 and (map[i][j].type==2 or map[i][j].type==3)):
                    map[i][j].army+=1
                    player[map[i][j].color].army+=1
                    map[i][j].lazytag=True
                if (turn%25==0 and map[i][j].color!=0):
                    map[i][j].army+=1
                    player[map[i][j].color].army+=1
                    map[i][j].lazytag=True
                if (map[i][j].type==4 and map[i][j].army!=0):
                    map[i][j].army-=1
                    player[map[i][j].color].army-=1
                    if map[i][j].army==0:
                        player[map[i][j].color].land-=1
                        map[i][j].color=0
                    map[i][j].lazytag=True
        p.goto(400,400)
        p.pendown()
        p.begin_fill()
        p.fillcolor("black")
        p.goto(600,400)
        p.goto(600,300-25*numofplayers)
        p.goto(400,300-25*numofplayers)
        p.goto(400,400)
        p.end_fill()
        p.penup()
        p.goto(450,350)
        p.write("color",font=('Arial',15,'normal'),align='center')
        for i in range(1,numofplayers+1):
            p.goto(450,350-25*i)
            p.write(color[player[i].color],font=('Arial',20,'normal'),align='center')
        p.goto(500,350)
        p.write("army",font=('Arial',15,'normal'),align='center')
        for i in range(1,numofplayers+1):
            p.goto(500,350-25*i)
            p.write(player[i].army,font=('Arial',20,'normal'),align='center')
        p.goto(550,350)
        p.write("land",font=('Arial',15,'normal'),align='center')
        for i in range(1,numofplayers+1):
            p.goto(550,350-25*i)
            p.write(player[i].land,font=('Arial',20,'normal'),align='center')
    system('cls')
    print ("winner:",end=" ")
    for i in range(1,numofplayers+1):
        if player[i].die==False:
            print(color[player[i].color])

_thread.start_new_thread(mymain,())
#监听
r1=1                                                    #状态：1为调兵，0为非调兵
r2=1                                                    #需要让玩家了解r的值，通过高亮颜色区分
por1=1                                                   #调兵比例：1为100%，0.5为50%,直到0.125为12.5%
por2=1
class Act:
    def __init__(self,fx,fy,tx,ty,num):
        self.fx=fx
        self.fy=fy
        self.tx=tx
        self.ty=ty
        self.num=num

def wasd(s,t):
    global por1
    x=player[1].highlight[0]
    y=player[1].highlight[1]
    if not (x+s in range(1,n+1) and y+t in range(1,m+1)): return
    if r1: 
        player[1].operate.put(Act(player[1].highlight[0],player[1].highlight[1],player[1].highlight[0]+s,player[1].highlight[1]+t,por1),False)
    player[1].highlight=[x+s,y+t]
    por1=1
    player[1].p.goto(800/min(m,n)*player[1].highlight[1]-400-400/min(m,n),-800/min(m,n)*player[1].highlight[0]+400+400/min(m,n))
    update()
    # palyer[1].p.stamp()
def pw():
    wasd(-1,0)
def pa():
    wasd(0,-1)
def ps():
    wasd(1,0)
def pd():
    wasd(0,1)
def pr():
    global r1
    r1^=1
def pt():
    global por1
    if por1==0.125:
        por1=1
    else: por1=por1/2

def uldr(s,t):
    global por2
    x=player[2].highlight[0]
    y=player[2].highlight[1]
    if not (x+s in range(1,n+1) and y+t in range(1,m+1)): return
    if r2: 
        player[2].operate.put(Act(player[2].highlight[0],player[2].highlight[1],player[2].highlight[0]+s,player[2].highlight[1]+t,por2),False)
    player[2].highlight=[x+s,y+t]
    por2=1
    player[2].p.goto(800/min(m,n)*player[2].highlight[1]-400-400/min(m,n),-800/min(m,n)*player[2].highlight[0]+400+400/min(m,n))
    update()
    # player[2].p.stamp()
def pup():
    uldr(-1,0)
def plf():
    uldr(0,-1)
def pdw():
    uldr(1,0)
def prg():
    uldr(0,1)
def pco():
    global r2
    r2^=1
def psl():
    global por2
    if por2==0.125:
        por2=1
    else: por2=por2/2
def optclear1():
    while not player[1].operate.empty():
        player[1].operate.get()
def optclear2():
    while not player[2].operate.empty():
        player[2].operate.get()


onkeypress(pw,'w')
onkeypress(pa,'a')
onkeypress(ps,'s')
onkeypress(pd,'d')
onkeypress(pr,'r')
onkeypress(pt,'t')
onkeypress(pup,'Up')
onkeypress(plf,'Left')
onkeypress(pdw,'Down')
onkeypress(prg,'Right')
onkeypress(pco,'.')
onkeypress(psl,'/')
onkeypress(optclear1,'q')
onkeypress(optclear2,'m')
listen()
mainloop()
